import html2canvas from 'html2canvas';

async function drawAnimatedWebpToCanvas(webpUrl: string, canvas: HTMLCanvasElement) {
  console.log('[drawAnimatedWebpToCanvas] 开始处理动态webp:', webpUrl);

  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous';

    img.onload = async () => {
      const ctx = canvas.getContext('2d');
      if (!ctx) {
        console.error('[drawAnimatedWebpToCanvas] 获取canvas上下文失败');
        reject(new Error('Failed to get canvas context'));
        return;
      }

      // 等待一段时间让动画播放到有内容的帧
      await new Promise(resolve => setTimeout(resolve, 100));

      // 绘制图片到canvas
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

      // 检查是否绘制了空白帧
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const pixels = imageData.data;
      let hasContent = false;

      // 检查像素数据是否都是透明的
      for (let i = 3; i < pixels.length; i += 4) {
        if (pixels[i] > 0) {
          // alpha 通道
          hasContent = true;
          break;
        }
      }

      if (!hasContent) {
        console.log('[drawAnimatedWebpToCanvas] 检测到空白帧，等待后重试');
        // 如果是空白帧，多等待一会儿再次尝试
        setTimeout(() => {
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          console.log('[drawAnimatedWebpToCanvas] 重试绘制完成');
          resolve(true);
        }, 500);
      } else {
        console.log('[drawAnimatedWebpToCanvas] 图片绘制完成，包含有效内容');
        resolve(true);
      }
    };

    img.onerror = error => {
      console.error('[drawAnimatedWebpToCanvas] 图片加载失败:', error);
      reject(error);
    };

    img.src = webpUrl;
  });
}

export async function canvasExportCoverWebpAndGif(canvasContainer: any, save = true) {
  console.log('[canvasExportCoverWebpAndGif] 开始导出, save:', save);
  const content = canvasContainer;

  // 处理所有 webp 图片
  const webpImages = content.querySelectorAll('img[src$=".webp"]');
  console.log('[canvasExportCoverWebpAndGif] 找到webp图片数量:', webpImages.length);

  for (const img of webpImages) {
    try {
      const isAnimated = await isAnimatedWebp(img.src);
      console.log('[canvasExportCoverWebpAndGif] 检查图片是否为动图:', img.src, isAnimated);

      if (isAnimated) {
        // 创建临时 canvas 处理动图
        const tempCanvas = document.createElement('canvas');
        tempCanvas.width = img.width || img.naturalWidth;
        tempCanvas.height = img.height || img.naturalHeight;

        let retryCount = 0;
        const maxRetries = 5;

        while (retryCount < maxRetries) {
          try {
            await drawAnimatedWebpToCanvas(img.src, tempCanvas);
            const newDataUrl = tempCanvas.toDataURL('image/png');

            // 检查生成的图片是否为空白
            const checkImg = new Image();
            await new Promise((resolve, reject) => {
              checkImg.onload = resolve;
              checkImg.onerror = reject;
              checkImg.src = newDataUrl;
            });

            const checkCanvas = document.createElement('canvas');
            checkCanvas.width = checkImg.width;
            checkCanvas.height = checkImg.height;
            const checkCtx = checkCanvas.getContext('2d');
            checkCtx?.drawImage(checkImg, 0, 0);

            const imageData = checkCtx?.getImageData(0, 0, checkCanvas.width, checkCanvas.height);
            const pixels = imageData?.data || new Uint8ClampedArray();
            let hasContent = false;

            for (let i = 3; i < pixels.length; i += 4) {
              if (pixels[i] > 0) {
                hasContent = true;
                break;
              }
            }

            if (hasContent) {
              img.src = newDataUrl;
              document.body.appendChild(tempCanvas);
              console.log('[canvasExportCoverWebpAndGif] 成功捕获有效帧');
              break;
            } else {
              console.log('[canvasExportCoverWebpAndGif] 捕获到空白帧，重试中...', retryCount + 1);
              retryCount++;
              await new Promise(resolve => setTimeout(resolve, 500));
            }
          } catch (error) {
            console.error('[canvasExportCoverWebpAndGif] 处理失败，重试中...', error);
            retryCount++;
          }
        }
      }
    } catch (error) {
      console.error('[canvasExportCoverWebpAndGif] 处理webp图片失败:', error);
    }
  }

  console.log('[canvasExportCoverWebpAndGif] 开始生成canvas');
  const canvas = await html2canvas(content, {
    scale: save ? 2 : 2, // 提高缩放比例以获得更高质量
    useCORS: true,
    allowTaint: false, // 不允许污染画布
    backgroundColor: null, // 透明背景
    logging: false, // 关闭日志提高性能
    imageTimeout: 0, // 禁用图片加载超时
    onclone: cb => {
      const moveableControlBox = cb.getElementsByClassName('moveable-control-box');
      Array.from(moveableControlBox).forEach((item: any) => {
        item.style.display = 'none';
      });
    }
  }).catch(error => {
    console.error('[canvasExportCoverWebpAndGif] html2canvas生成失败:', error);
    throw error;
  });

  console.log('[canvasExportCoverWebpAndGif] 导出完成');
  const dataURL = canvas.toDataURL('image/png', 0.8);
  return dataURL;
}

// 检查是否为动态 webp
async function isAnimatedWebp(url: string): Promise<boolean> {
  console.log('[isAnimatedWebp] 开始检查:', url);
  try {
    const response = await fetch(url);
    const buffer = await response.arrayBuffer();
    const view = new Uint8Array(buffer);

    // WebP 文件格式检查
    // 1. 检查 RIFF 头部
    if (view[0] !== 0x52 || view[1] !== 0x49 || view[2] !== 0x46 || view[3] !== 0x46) {
      console.log('[isAnimatedWebp] 不是有效的 WebP 文件');
      return false;
    }

    // 2. 检查 WEBP 标识
    if (view[8] !== 0x57 || view[9] !== 0x45 || view[10] !== 0x42 || view[11] !== 0x50) {
      console.log('[isAnimatedWebp] 不是有效的 WebP 文件');
      return false;
    }

    // 3. 查找 'ANIM' 块
    // 将二进制数据转换为字符串进行搜索
    const bytes = new Uint8Array(buffer);
    const content = Array.from(bytes)
      .map(byte => String.fromCharCode(byte))
      .join('');

    const hasANMF = content.includes('ANMF');
    const hasANIM = content.includes('ANIM');

    console.log('[isAnimatedWebp] 检查结果:', {
      url,
      hasANMF,
      hasANIM,
      fileSize: buffer.byteLength
    });

    // 同时包含 ANIM 和 ANMF 块才是动态 WebP
    return hasANMF && hasANIM;
  } catch (error) {
    console.error('[isAnimatedWebp] 检查失败:', url, error);
    return false; // 检查失败时返回 false 而不是抛出错误
  }
}
